(function ($) {
    $.fn.zkTree = function (options) {
        var defaults = {
            treeId: null,
            parentIsNode: false,
            view: {dblClickExpand: false, selectedMulti: false},
            data: {key: {name: "MC"}, simpleData: {enable: true, idKey: "DM", pIdKey: "SJDM"}},
            callback: {onClick: null},
            panel: {height: '16em'},
            tree_data: null
        };
        var settings = $.extend({}, defaults, options);
        return this.each(function () {
            var $this = $(this);
            var random = Math.floor(Math.random() * 100) + 1;
            var treeId = "tree_" + random;
            if (settings.treeId) {
                treeId = settings.treeId;
            }
            var $zTree = $('<div class="panel panel-default ztreePanel" style="display:none;position: absolute;border:1px solid rgb(170,170,170);z-index:1000;overflow: auto;">').css("height", settings.panel.height).append($('<ul class="ztree"></ul>').attr("id", treeId)).insertAfter($this);
            $this.click(function () {
                var width = $this.css("width");
                var cityOffset = $this.position();
                $this.next().css({
                    left: cityOffset.left,
                    top: cityOffset.top + $this.outerHeight()
                }).slideDown("fast").css("width", parseInt(width));
                $("body").bind("mousedown", onBodyDown);
            });
            function hideMenu() {
                $this.next().fadeOut("fast");
                $("body").unbind("mousedown", onBodyDown);
            };
            function onBodyDown(event) {
                if ($(event.target).closest("div.ztreePanel", $this).size() < 1) {
                    hideMenu();
                }
            };

            $.fn.zTree.init($zTree.children(), settings, settings.tree_data);

        });
    }
})(jQuery);


function swjg_change(callback){
    var url = "/dzswjglpt/sbdm/querySwjgDm/.do";
    $.ajax({
        url : url,
        dataType : 'json',
        contentType:"application/json",
        type : 'get',
        async : false,
        success : function(response) {
            if(response.resultCode=="000000"){
                var optionobj = response.resultObj.resultObj;

                tellisParent(optionobj)

                var options_swjg = {
                    treeId:"swjgtree",
                    tree_data:optionobj,
                    callback:{
                        onClick:function(event, treeId, treeNode) {//点击菜单时进行的处理
                            $("#swjgdm").val(treeNode.MC);
                            $("#swjg_dm").val(treeNode.DM);
                            $("#swjgtree").hide();
                            $(".panel").hide();
                            if(callback){
                                callback(treeNode);
                            }
                        },
                        onExpand: function (event, treeId, treeNode) {

                            if (!treeNode.isParent){return;}
                            if (treeNode.children != undefined){return;}

                            var url = "/dzswjglpt/sbdm/querySwjgDm/"+treeNode.DM+'.do';
                            $.ajax({
                                url : url,
                                dataType : 'json',
                                contentType:"application/json",
                                type : 'get',
                                success : function(response) {
                                    if(response.resultCode=="000000"){

                                        var optionobj = response.resultObj.resultObj;
                                        tellisParent(optionobj)

                                        var swjgZTree = $.fn.zTree.getZTreeObj(treeId);

                                        swjgZTree.addNodes(treeNode, optionobj);

                                    }else{
                                        bootbox.alert('获取税务机关失败');
                                    }
                                },
                                error : function() {
                                    bootbox.alert("获取税务机关错误！");
                                }
                            });
                        }
                    }
                }
                $("#swjgdm").zkTree(options_swjg);
                if(optionobj!=null && optionobj.length>0){
                	 $("#swjgdm").val(optionobj[0].MC);
                     $("#swjg_dm").val(optionobj[0].DM);
                }
               
                
            }
        },
        error : function() {
            bootbox.alert("获取基础信息异常！");
        }
    });
}
function tellisParent(obj) {
    $.each(obj,function (i,item) {
        if(item.ISPARENT && item.ISPARENT > 0){
            item.isParent = true
        }else{
            item.isParent = false
        }
    })
}



function xzqh_change(){
    var url = "/dzswjglpt/sbdm/getSwXzqh/.do";
    $.ajax({
        url : url,
        dataType : 'json',
        contentType:"application/json",
        type : 'get',
        success : function(response) {
            if(response.resultCode=="000000"){
                var optionobj = response.resultObj.resultObj;
                $.each(optionobj,function (i,item) {
                    if(item.SJDM ){
                        item.SJDM = item.SJDM.replace('#','~');
                    }
                    item.DM = item.DM.replace('#','~');
                    item.isParent = true
                })

                var options_swjg = {
                    treeId:"xzqhtree",
                    tree_data:optionobj,
                    callback:{
                        onClick:function(event, treeId, treeNode) {//点击菜单时进行的处理
                            $("#xzqhmc").val(treeNode.MC);
                            $("#xzqh").val(treeNode.DM);
                            $("#xzqhtree").hide();

                           
                        },
                        onExpand: function (event, treeId, treeNode) {
                            if (!treeNode.isParent){return;}
                            if (treeNode.children != undefined){return;}
                            var url = "/dzswjglpt/sbdm/getSwXzqh/"+treeNode.DM+'.do';
                            $.ajax({
                                url : url,
                                dataType : 'json',
                                contentType:"application/json",
                                type : 'get',
                                success : function(response) {
                                    if(response.resultCode=="000000"){

                                        var optionobj = response.resultObj.resultObj;
                                        tellXzqhIsParent(optionobj)

                                        var xzqhZTree = $.fn.zTree.getZTreeObj(treeId);

                                        xzqhZTree.addNodes(treeNode, optionobj);

                                    }else{
                                        bootbox.alert('获取行政区划失败');
                                    }
                                },
                                error : function() {
                                    bootbox.alert("获取行政区划错误！");
                                }
                            });
                        }
                    }
                }
                $("#xzqhmc").zkTree(options_swjg);
            }
        },
        error : function() {
            bootbox.alert("获取行政区划错误！");
        }
    });
}
function tellXzqhIsParent(obj){

    $.each(obj,function (i,item) {
        if(item.SJDM ){
            item.SJDM = item.SJDM.replace('#','~');
        }
        item.DM = item.DM.replace('#','~');

        var isxzqh = item.DM.indexOf('～1') > -1 && item.ISPARENT == 0;
        var isxzjd = item.DM.indexOf('～1') == -1 && item.ISPARENT > 0;

        if(isxzjd || isxzqh){
            item.isParent = true
        }else{
            item.isParent = false
        }
    })

}

Array.prototype.remove = function(item) {
    for(var i = 0,n = this.length;i < n; i++) {
       if(this[i] == item) {
           this.splice(i, 1);
           break;
       }
   }
};


//行政区划多选
function xzqh_change_check(){

    var url = "/dzswjglpt/sbdm/getSwXzqh/.do";
    $.ajax({
        url : url,
        dataType : 'json',
        contentType:"application/json",
        type : 'get',
        success : function(response) {
            if(response.resultCode=="000000"){
                var optionobj = response.resultObj.resultObj;
                $.each(optionobj,function (i,item) {
                    if(item.SJDM ){
                        item.SJDM = item.SJDM.replace('#','~');
                    }
                    item.DM = item.DM.replace('#','~');
                    item.isParent = true
                })
                var options_swjg = {
                    treeId:"xzqhtree",
                    tree_data:optionobj,
                    check: {
                        enable: true,
                        chkStyle:"checkbox",
                        chkboxType:{"Y":"","N":""}
                    },
                    callback:{
                        onExpand: function (event, treeId, treeNode) {
                            if (!treeNode.isParent){return;}
                            if (treeNode.children != undefined){return;}
                            var url = "/dzswjglpt/sbdm/getSwXzqh/"+treeNode.DM+'.do';
                            $.ajax({
                                url : url,
                                dataType : 'json',
                                contentType:"application/json",
                                type : 'get',
                                success : function(response) {
                                    if(response.resultCode=="000000"){

                                        var optionobj = response.resultObj.resultObj;
                                        tellXzqhIsParent(optionobj)

                                        var xzqhZTree = $.fn.zTree.getZTreeObj('xzqhtree');

                                        xzqhZTree.addNodes(treeNode, optionobj);

                                    }else{
                                        bootbox.alert('获取行政区划失败');
                                    }
                                },
                                error : function() {
                                    bootbox.alert("获取行政区划错误！");
                                }
                            });
                        },
                        onCheck:function(event, treeId, treeNode) {//点击菜单时进行的处理
                            if(treeNode.checked==true){
                                addXzqh(treeId,treeNode);
                            }else{
                                removeXzqh(treeNode);
                            }
                        }
                    }
                }
                $("#xzqhmc").zkTree(options_swjg);
            }
        },
        error : function() {
            bootbox.alert("获取行政区划错误！");
        }
    });


    var xzqhmcs = [];
    var xzqhdms = [];
	
	/*var xnhdzfwdm_arr = xnhdzfwdm.split(",");// 在每个逗号(,)处进行分解  
		var arr_1=new Array();
		var arr_2=new Array();
		var arr_3=new Array();
		
		$.each(xnhdzfwdm_arr,function(i,n){
			var xzqh_ws=n.substr(n.length-1,1);
			if(xzqh_ws==1){
				arr_1.push(xzqh_ws);
			}else if(xzqh_ws==2){
				arr_2.push(xzqh_ws);
			}else if(xzqh_ws==3){
				arr_3.push(xzqh_ws);
			}
		});
		if(arr_1.length>0&&arr_2.length>0||
		arr_1.length>0&&arr_3.length>0||
		arr_2.length>0&&arr_3.length>0||
		arr_1.length>0&&arr_2.length>0&&arr_3.length>0
		){
			bootbox.alert("行政区划只能选择同一级，不能跨级选择！");
			return;
		}*/
    //代征范围勾选添加
    function addXzqh(treeId,treeObj){
        xzqhmcs.push(treeObj.MC);
        xzqhdms.push(treeObj.DM);
		
		//var xnhdzfwdm_arr_1= xzqhdms.split(",");// 在每个逗号(,)处进行分解  
		var arr_1_1=new Array();
		var arr_2_2=new Array();
		var arr_3_3=new Array();
		
		$.each(xzqhdms,function(i,n){
			var xzqh_ws_1=n.substr(n.length-1,1);
			if(xzqh_ws_1==1){
				arr_1_1.push(xzqh_ws_1);
			}else if(xzqh_ws_1==2){
				arr_2_2.push(xzqh_ws_1);
			}else if(xzqh_ws_1==3){
				arr_3_3.push(xzqh_ws_1);
			}
		});
		if(arr_1_1.length>0&&arr_2_2.length>0||
		arr_1_1.length>0&&arr_3_3.length>0||
		arr_2_2.length>0&&arr_3_3.length>0||
		arr_1_1.length>0&&arr_2_2.length>0&&arr_3_3.length>0
		){
			xzqhmcs.remove(treeObj.MC);
        xzqhdms.remove(treeObj.DM);
		treeObj.check_Focus=false;
		treeObj.checked=false;
		assignDmAndMc(xzqhmcs,xzqhdms)	
			bootbox.alert("行政区划只能选择同一级，不能跨级选择！");
			
		}else{
		assignDmAndMc(xzqhmcs,xzqhdms)	
		}
			
		
		
		
        
        // if(treeObj.children){
        //     for (var i = 0; i < treeObj.children.length; i++) {
        //         if(treeObj.children[i].children){
        //             addXzqh(treeId,treeObj.children[i]);
        //         }else{
        //             //勾选父级 子级自动勾选
        //             var tree = $.fn.zTree.getZTreeObj(treeId);
        //             var node = tree.getNodes();
        //             var nodes = tree.transformToArray(node);
        //             for(var j=0;j<nodes.length;j++){
        //                 if(nodes[j].DM==treeObj.children[i].DM){
        //                     tree.checkNode(nodes[j], true, true);
        //                 }
        //             }
        //             //回显塞数据
        //             xzqhmcs.push(treeObj.children[i].MC);
        //             xzqhdms.push(treeObj.children[i].DM);
        //             $("#xzqhmc").val(xzqhmcs.join());
        //             $("#xzqh").val(xzqhdms.join());
        //         }
        //     }
        // }
		
		
		
    }
//代征范围勾选移除
function removeXzqh(treeObj){
        // if(treeObj.children){
        //     for (var i = 0; i < treeObj.children.length; i++) {
        //         if(treeObj.children[i].children){
        //             removeXzqh(treeObj.children[i]);
        //         }else{
        //             xzqhmcs.remove(treeObj.children[i].MC);
        //             xzqhdms.remove(treeObj.children[i].DM);
        //             assignDmAndMc(xzqhmcs,xzqhdms)
        //         }
        //     }
        // }

        xzqhmcs.remove(treeObj.MC);
        xzqhdms.remove(treeObj.DM);
        assignDmAndMc(xzqhmcs,xzqhdms)
    }


function assignDmAndMc(xzqhmcs,xzqhdms){
    $("#xzqhmc").val(unique(xzqhmcs).join());
    $("#xzqh").val(unique(xzqhdms).join());
}

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    var array = [];
    for (var i = 0; i < arr.length; i++) {
        if (array .indexOf(arr[i]) === -1) {
            array .push(arr[i])
        }
    }
    return array;
}

}


   


